package utils

import (
	"github.com/Unknwon/goconfig"
	"os/user"
	"path/filepath"
)

func GetStoreFile() map[string]string {
	us, err := user.Current(); if err != nil {
		return make(map[string]string)
	}
	cfg, err := goconfig.LoadConfigFile(filepath.Join(us.HomeDir, ".gend", "machine.ini")); if err != nil {
		return make(map[string]string)
	}

	res := make(map[string]string)
	for _, section := range cfg.GetSectionList() {
		for _, key := range cfg.GetKeyList(section) {
			v, err := cfg.GetValue(section, key); if err != nil {
				return make(map[string]string)
			}
			res[key] = v
		}
	}
	return res
}

func WriteKey(key string, value string) error {
	us, err := user.Current(); if err != nil {
		return err
	}
	cfg, err := goconfig.LoadConfigFile(us.HomeDir); if err != nil {
		return err
	}

	cfg.SetValue("key_default", key, value)
	return goconfig.SaveConfigFile(cfg, filepath.Join(us.HomeDir, ".gend", "machine.ini"))
}

func DumpFile(mp map[string]string) error {
	us, err := user.Current(); if err != nil {
		return err
	}
	cfg, err := goconfig.LoadConfigFile(us.HomeDir); if err != nil {
		return err
	}
	for key, value := range mp {
		cfg.SetValue("key_default", key, value)
	}

	return goconfig.SaveConfigFile(cfg, filepath.Join(us.HomeDir, ".gend", "machine.ini"))
}